function cwndplot(fname,trange,yrange)
% CWNDPLOT    Plot estimated RTT and RTO.
%    CWNDPLOT(FILENAME) plots the specified file with RTT and RTO.
%    Column 1 is time. The other two column is RTT and RTO respectivly.
%
%    CWNDPLOT(FILENAME,TIMERANGE) plots the specified data file
%    with time range TIMERANGE.
%
%    CWNDPLOT(FILENAME,TIMERANGE,YRANGE) plots the specified data file
%    with time range TIMERANGE and Y value range YRANGE.
%
%    Example:
%       cwndplot('cwnddump_1_100.out');
%       cwndplot('cwnddump_1_100.out', [192 196]);
%       cwndplot('cwnddump_1_100.out', [192 196], [0.01 1.01]);

if (nargin < 1) | (nargin > 3)
   error('Wrong number of input arguments. Try help rttplot.');
end

if nargin > 1
   stime = trange(1);
   etime = trange(2);
else
   stime = -1;
end

if nargin > 2
   miny = yrange(1);
   maxy = yrange(2);
else
   miny = -1;
end

ldcmd = sprintf('load %s;', fname);
eval(ldcmd);
fnamehd = strtok(fname, '.');
asgncmd = sprintf('D = %s;', fnamehd);
eval(asgncmd);
clrcmd = sprintf('%s = [];', fnamehd);
eval(clrcmd);

[row col] = size(D);
if col < 3
   error('Not enough columns in rtt file.');
end

if stime >= 0
   T = [];
   numT = 0;
   for i=1:row
      if (stime <= D(i,1)) & (D(i,1) <= etime)
         numT = numT + 1;
	 T(numT,:) = D(i,:);
      end
   end
   D = T;
   T = [];
end
%set(gcf,'Units','pixels');
%set(gcf,'Position',[20 20 800 600]);

tplot = 0;
if (~isempty(D)) & (max(D(:,2)) >= 0)
  plot(D(:,1),D(:,2),':ob','MarkerSize',2);
  tplot = 1;
end
hold on;
oplot = 0;
if (~isempty(D)) & (max(D(:,3)) >= 0)
  plot(D(:,1),D(:,3),':or','MarkerSize',2);
  oplot = 1;
end
aplot = 0;
if (~isempty(D)) & (max(D(:,4)) >= 0)
  plot(D(:,1),D(:,4),':om','MarkerSize',2);
  aplot = 1;
end

xlabel('Time (seconds)');
ylabel('cwnd, rwnd & ssthresh (bytes)');

if tplot == 1
   lgndcmd = '''cwnd'', ';
else 
   lgndcmd = '';
end
if oplot == 1
   lgndcmd = strcat(lgndcmd, '''ssthresh'', ');
end
if aplot == 1
   lgndcmd = strcat(lgndcmd, '''rwnd'', ');
end

if ~isempty(lgndcmd)
   lgndcmd = sprintf('legend(%s 2);', lgndcmd);
   eval(lgndcmd);
end
grid on;
hold off;

if miny >= 0
   set(gca, 'YLim', [miny maxy]);
end

fn = strrep(fname,'_','\_');
titcmd = sprintf('title(''%s'');', fn);
eval(titcmd);

[I,map] = capture;
imcmd = sprintf('imwrite(I,map,''%s.jpg'',''jpeg'');', fnamehd);
eval(imcmd);

set(gcf,'PaperUnits','points');
set(gcf,'PaperPosition',[20 20 800 600]);
print(gcf, '-depsc', fnamehd);

